//
//  SWUploadManager.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/9/29.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation

private let _manager:SWUploadManager = SWUploadManager()
class SWUploadManager: NSObject,SWAPIComponent
{
    private var _launched:Bool = false
    private var _fileManager = FileManager.default
    private var _tasks:[SWUploadTask] = []
    private var _documentPath:String = ""
    private var _dataPath:String = ""
    private var _task:SWUploadTask?
    private var _addTaskIntervalID:String = ""
    private let _queue:OperationQueue = OperationQueue()
    
    var uploaders:[SWPageUploader] = []
    
    //上传进展情况保存在本地，app打开后在wifi情况下进行上传
    class func sharedManager() -> SWUploadManager
    {
        return _manager
    }
    
    func launch()
    {
        if !_launched
        {
            _launched = true
            
            _documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? ""
            _dataPath = "\(_documentPath)/uploadtask.data"
            
            //未完成任务下载
            pause()
            if let tasks = SWCacheManager.sharedManager().readCache(_dataPath) as? [SWUploadTask]
            {
                print("tasks:", tasks.count)
                for task in tasks
                {
                    if let relativePath = task.relativePath, relativePath != ""
                    {
                        let localPath = SWPageManager.sharedManager().fetchStorePath(relativePath: relativePath)
                        task.localPath = localPath
                        
                        addTask(task, autoStart: false)
                        
                    }//end relativePath
                }//end for
            }//end if tasks
            resume()
            
            
            
        }//end _launched
    }
    
    //暂停任务
    func pause()
    {
        _queue.isSuspended = true
    }
    
    //恢复任务
    func resume()
    {
        _queue.isSuspended = false
    }
    
    //当有上传任务加入时，如果历史中有记录，应将记录设为未完成
    func addTask(_ task:SWUploadTask, autoStart:Bool = true)
    {
        //过滤无效任务
        guard let localPath = task.localPath, localPath != "" else{
                return
        }
        
        if autoStart
        {
            pause()
        }
        
        //如果队列中未包含此项或者此项未下载完成
        if let index = _tasks.index(where: {($0.localPath ?? "") == localPath}),
            let task = _tasks.valueAt(index)
        {
            task.finished = false
            //_tasks[index] = task
        }
        else
        {
            _tasks.append(task)
        }
        
        print("addUploadTask:", _tasks.count)
        
        if let operations = _queue.operations as? [SWUploadOperation],
           let index = operations.index(where: {$0.localPath == localPath}),
           let operation = operations.valueAt(index)
        {
            operation.update(task)
            print("任务已在队列中")
        }
        else
        {
            if let operation = SWUploadOperation(task: task)
            {
                operation.successCallback = {[weak self] response in self?.uploadSuccess(response)}
                _queue.addOperation(operation)
            }
            
            print("_queue.operations:", _queue.operations.count)
        }
        
        save()
        clearTimeout(_addTaskIntervalID)
        if autoStart
        {
            //生成一段时间之后再上传（频繁修改频繁生成，但上传频率会限制）
            _addTaskIntervalID = setTimeout(5, closure: {[weak self] in
                self?.resume()
                })
        }
    }
    
    private var _batchQueue:OperationQueue = OperationQueue()
    func uploadAllPage(_ book:SWBook, successCallback:@escaping ()->Void)
    {
        _batchQueue.maxConcurrentOperationCount = 2
        if var pages:[SWPage] = book.pages?.flatMap({$0 as? SWPage})
        {
            let clonePages = pages
            let t1 = NSDate().timeIntervalSince1970
            //pages += pages //8
            //pages += pages //16
//            pages += pages //32
//            pages += clonePages //36
//            pages += clonePages //40
            //pages += pages //64页
            print("pages:", pages.count)
            for page in pages
            {
                if SWPageManager.sharedManager().productExists(page, level: .origin)
                {
                    let localPath = SWPageManager.sharedManager().fetchStorePath(page, level: .origin)
                    let task = SWUploadTask(page: page)
                    task.localPath = localPath
                    if let operation = SWUploadOperation(task: task)
                    {
                        operation.completionBlock = {[weak self] in
                            let operationCount:Int = self?._batchQueue.operationCount ?? 0
                            if operationCount == 0
                            {
                                successCallback()
                                print("总耗时:", NSDate().timeIntervalSince1970 - t1)
                            }
                        }
                        self._batchQueue.addOperation(operation)
                    }
                    
                    //tasks.append(task)
                }
            }
            
        }
    }
    
    //订单图片上传保存处理
    private func orderUploadUpdateHander(_ record:SWOrderRecord, uploadRightNow:Bool = false)
    {
        let pages:[SWPage] = record.pages?.flatMap({$0 as? SWPage}) ?? []
        if pages.count > 0
        {
            //已经全部上传
            //record.valid &&
            let orderID:String = record.orderID ?? ""
            if record.uploadedPages.count >= pages.count
            {
                orderPagesUpdate(orderID:orderID, pages:pages)
                //
                NotificationCenter.default.post(name: NotificationName.UploadProgressChanged, object: nil, userInfo: [SWKey.orderID:orderID, SWKey.progress:1])
            }
            else
            {
                let uploader:SWPageUploader = SWUploadManager.sharedManager().fetchUploader(id: orderID) ?? SWPageUploader(record: record)
                if uploadRightNow
                {
                    uploader.resume()
                }
                SWUploadManager.sharedManager().addUploader(uploader)
                trace("未上传完成的订单:", record.orderID)
            }
        }
        else
        {
            trace("当前订单无图片")
        }
    }
    
    //保存订单图片
    private func orderPagesUpdate(orderID:String, pages:[SWPage])
    {
        let req:SWOrderPagesUpdateReq = SWOrderPagesUpdateReq()
        req.pages = pages
        req.orderID = orderID
        req.successCallback = {[weak self] response,_ in
            SWNotificationCenter.post(name: NotificationName.OrderPagesUpdateComplete, object: nil, userInfo: [SWKey.orderID:orderID])
        }
        req.failCallback = {[weak self] error in
            //SVProgressHUD.showError(withStatus: error.message)
        }
        load(req)
        
        //UIApplication.shared.windows
    }
    
    func fetchUploader(id:String) -> SWPageUploader?
    {
        if let index = uploaders.index(where: {$0.id == id})
        {
            return uploaders.valueAt(index)
        }
        return nil
    }
    
    //每个订单都有一个独立的Uploader
    func addUploader(_ uploader:SWPageUploader)
    {
        if !uploaders.contains(where: {$0.id == uploader.id})
        {
            uploaders.append(uploader)
        }
    }
    
    func removeUploader(id:String)
    {
        if let index = uploaders.index(where: {$0.id == id})
        {
            uploaders.removeAtIndexSafely(index)
        }
    }
    
    func upload(record:SWOrderRecord, rightNow:Bool)
    {
        orderUploadUpdateHander(record, uploadRightNow: rightNow)
    }
    
    func uploadAll()
    {
        for uploader in uploaders
        {
            if !uploader.running
            {
                uploader.resume()
            }
        }
    }
    
    func pauseAll()
    {
        for uploader in uploaders
        {
            if uploader.running
            {
                uploader.pause()
            }
        }
    }
    
    private func save()
    {
        SWCacheManager.sharedManager().writeCache(_tasks, path: _dataPath)
    }
    
    private func uploadFail()
    {
        
    }
    
    private func uploadSuccess(_ response:SWUploadResponse)
    {
        //生成完成后从队列中删除
        if let index = _tasks.index(where: {($0.localPath ?? "") == response.localPath}) {
            _tasks.removeAtIndexSafely(index)
        }
        
        if let page = SWBookManager.sharedManager().fetchPage(bookID: response.bookID, pageID: response.pageID)
        {
            if response.origin
            {
                page.largeResultURL = response.url
            }
            else
            {
                page.previewResultURL = response.url
            }
        }
        
        save()
    }
    
    
    
    
    
}//end class

